package com.exampl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.exampl.common.R;
import com.exampl.domain.Category;
import com.exampl.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    // 获取分类
    @GetMapping("/page")
    public R<IPage<Category>> page(int page, int pageSize){
        IPage<Category> iPage = categoryService.getPage(page, pageSize);
        return R.success(iPage);
    }

    // 添加分类
    @PostMapping
    public R<String> add(@RequestBody Category category){
        String name = category.getName();
        Category one = categoryService.FindByName(name);
        // 查看当前添加分类是否被逻辑删除
        if(one != null && one.getIsDeleted() == 1){
            categoryService.updateDelete(one.getId());
        }else {
            categoryService.save(category);
        }
        return R.success("添加成功！");
    }

    // 删除分类
    @DeleteMapping
    public R<String> delete(Long ids){
        categoryService.remove(ids);
        return R.success("删除成功");
    }

    // 修改分类
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功！");
    }

    // 获取下拉框的分类
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<Category>();
        lqw.eq(type != null, Category::getType, type);
        lqw.orderByAsc(Category::getSort);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
